package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV2;
import com.atguigu.realtime.bean.OrderWide;
import com.atguigu.realtime.bean.PaymentWide;
import com.atguigu.realtime.bean.ProductStats;
import com.atguigu.realtime.common.GmallConstant;
import com.atguigu.realtime.util.MyDimUtil;
import com.atguigu.realtime.util.MyKafkaUtil;
import com.atguigu.realtime.util.MySinkUtil;
import com.atguigu.realtime.util.MyTimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/4/26 10:16
 */
public class DWSProductStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        String[] topics = {
            "dwd_display",
            "dwd_favor_info",
            "dwd_cart_info",
            "dwm_order_wide",
            "dwm_payment_wide",
            "dwd_comment_info",
            "dwd_order_refund_info"
        };
        new DWSProductStatsApp().init(4002, 2, "DWSProductStatsApp", "DWSProductStatsApp", "dwd_page", topics);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> streams) {
        // 1. 多个流合并为一个流
        DataStream<ProductStats> productStatsStream = parseStreamsAndUnionOn(streams);
        // 2. 聚合
        SingleOutputStreamOperator<ProductStats> productStatsAggStream = aggregate(productStatsStream);
        // 3. join维度
        SingleOutputStreamOperator<ProductStats> productStatsWithDimStream = joinDim(productStatsAggStream);
        
        // 4. 写入到clickhouse中
        send2ClickHouse(productStatsWithDimStream);
        // 5. 补充把商品主题宽表写入到Kafka中 TODO  dws_product_stats
        send2Kafka(productStatsWithDimStream);
    
    }
    
    private void send2Kafka(SingleOutputStreamOperator<ProductStats> productStatsWithDimStream) {
        productStatsWithDimStream
            .map(JSON::toJSONString)
            .addSink(MyKafkaUtil.getKafkaSink("dws_product_stats"));
    }
    
    private void send2ClickHouse(SingleOutputStreamOperator<ProductStats> stream) {
        stream.addSink(MySinkUtil.getClickHouseSink("gmall2021", "product_stats_2021", ProductStats.class));
    }
    
    private SingleOutputStreamOperator<ProductStats> joinDim(SingleOutputStreamOperator<ProductStats> productStatsAggStream) {
      return  AsyncDataStream.unorderedWait(
            productStatsAggStream,
            new DimAsyncFunction<ProductStats>() {
                @Override
                protected void addDim(ProductStats input,
                                      Connection conn,
                                      Jedis client) {
                    
                    // 1. 补齐skuInfo
                    JSONObject skuInfo = MyDimUtil.readDim(conn, client, "dim_sku_info", input.getSku_id());
                    input.setSku_name(skuInfo.getString("SKU_NAME")); // shift + ctrl + u 大小写转换
                    input.setSku_price(skuInfo.getBigDecimal("PRICE"));
                    
                    // 从其他维度表读取数据的时候使用
                    input.setSpu_id(skuInfo.getLong("SPU_ID"));
                    input.setTm_id(skuInfo.getLong("TM_ID"));
                    input.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                    
                    // 2. 补齐spu
                    JSONObject spuInfo = MyDimUtil.readDim(conn, client, "dim_spu_info", input.getSpu_id());
                    input.setSpu_name(spuInfo.getString("SPU_NAME"));
                    
                    // 3. 补齐品牌
                    JSONObject tmInfo = MyDimUtil.readDim(conn, client, "dim_base_trademark", input.getTm_id());
                    input.setTm_name(tmInfo.getString("TM_NAME"));
                    
                    // 3. 补齐三级品类
                    JSONObject c3Info = MyDimUtil.readDim(conn, client, "dim_base_category3", input.getCategory3_id());
                    input.setCategory3_name(c3Info.getString("NAME"));
                }
            },
            30,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<ProductStats> aggregate(DataStream<ProductStats> productStatsStream) {
        return productStatsStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<ProductStats>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                    .withTimestampAssigner((ps, ts) -> ps.getTs())
            )
            .keyBy(ProductStats::getSku_id)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<ProductStats>() {
                    @Override
                    public ProductStats reduce(ProductStats v1,
                                               ProductStats v2) throws Exception {
                        v1.setDisplay_ct(v1.getDisplay_ct() + v2.getDisplay_ct());
                        v1.setClick_ct(v1.getClick_ct() + v2.getClick_ct());
                        v1.setCart_ct(v1.getCart_ct() + v2.getCart_ct());
                        v1.setFavor_ct(v1.getFavor_ct() + v2.getFavor_ct());
                        v1.setOrder_amount(v1.getOrder_amount().add(v2.getOrder_amount()));
                        
                        v1.setOrder_sku_num(v1.getOrder_sku_num() + v2.getOrder_sku_num());
                        v1.setPayment_amount(v1.getPayment_amount().add(v2.getPayment_amount()));
                        v1.setRefund_amount(v1.getRefund_amount().add(v2.getRefund_amount()));
                        v1.setRefund_amount(v1.getRefund_amount().add(v2.getRefund_amount()));
                        v1.setComment_ct(v1.getComment_ct() + v2.getComment_ct());
                        v1.setGood_comment_ct(v1.getGood_comment_ct() + v2.getGood_comment_ct());
                        
                        // 把三个集合合并在一起
                        v1.getOrderIdSet().addAll(v2.getOrderIdSet());
                        v1.getRefundOrderIdSet().addAll(v2.getRefundOrderIdSet());
                        v1.getPaidOrderIdSet().addAll(v2.getPaidOrderIdSet());
                        return v1;
                    }
                },
                new ProcessWindowFunction<ProductStats, ProductStats, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<ProductStats> elements,
                                        Collector<ProductStats> out) throws Exception {
                        ProductStats ps = elements.iterator().next();
                        TimeWindow w = ctx.window();
                        ps.setStt(MyTimeUtil.toDateTimeString(w.getStart()));
                        ps.setEdt(MyTimeUtil.toDateTimeString(w.getEnd()));
                        
                        ps.setOrder_ct((long) ps.getOrderIdSet().size());
                        ps.setPaid_order_ct((long) ps.getPaidOrderIdSet().size());
                        ps.setRefund_order_ct((long) ps.getRefundOrderIdSet().size());
                        
                        out.collect(ps);
                    }
                }
            );
    }
    
    private DataStream<ProductStats> parseStreamsAndUnionOn(Map<String, DataStreamSource<String>> streams) {
        // 1. 计算页面点击
        SingleOutputStreamOperator<ProductStats> productClickStream = streams
            .get("dwd_page")
            .flatMap(new FlatMapFunction<String, ProductStats>() {
                @Override
                public void flatMap(String json,
                                    Collector<ProductStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(json);
                    JSONObject pageObj = obj.getJSONObject("page");
                    String pageId = pageObj.getString("page_id");
                    if ("good_detail".equals(pageId)) {
                        Long skuId = pageObj.getLong("item");
                        Long ts = obj.getLong("ts");
                        ProductStats productStats = new ProductStats();
                        productStats.setTs(ts);
                        productStats.setSku_id(skuId);
                        productStats.setClick_ct(1L);
                        
                        out.collect(productStats);
                    }
                }
            });
        
        // 2. 曝光流
        SingleOutputStreamOperator<ProductStats> displayStream = streams
            .get("dwd_display")
            .process(new ProcessFunction<String, ProductStats>() {
                @Override
                public void processElement(String json,
                                           Context ctx,
                                           Collector<ProductStats> out) throws Exception {
                    JSONObject obj = JSON.parseObject(json);
                    if ("sku_id".equals(obj.getString("item_type"))) {
                        ProductStats ps = new ProductStats();
                        ps.setSku_id(obj.getLong("item"));
                        ps.setTs(obj.getLong("ts"));
                        ps.setDisplay_ct(1L);
                        
                        out.collect(ps);
                    }
                }
            });
        // 3. 收藏流
        SingleOutputStreamOperator<ProductStats> favorStream = streams
            .get("dwd_favor_info")
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setTs(MyTimeUtil.getTs(obj.getString("create_time"), "yyyy-MM-dd HH:mm:ss"));
                ps.setFavor_ct(1L);
                return ps;
            });
        // 4. 购物车流
        SingleOutputStreamOperator<ProductStats> cartStream = streams
            .get("dwd_cart_info")
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setTs(MyTimeUtil.getTs(obj.getString("create_time"), "yyyy-MM-dd HH:mm:ss"));
                ps.setCart_ct(1L);
                return ps;
            });
        // 5. 订单宽表流
        SingleOutputStreamOperator<ProductStats> orderWideStream = streams
            .get("dwm_order_wide")
            .map(json -> {
                OrderWide orderWide = JSON.parseObject(json, OrderWide.class);
                ProductStats ps = new ProductStats();
                ps.setSku_id(orderWide.getSku_id()); // TODO
                ps.setTs(MyTimeUtil.getTs(orderWide.getCreate_time()));
                ps.getOrderIdSet().add(orderWide.getOrder_id());
                
                ps.setOrder_amount(orderWide.getSplit_total_amount());
                ps.setOrder_sku_num(orderWide.getSku_num());
                
                // 注意: 订单个数等到聚合后, 读取set集合的长度进行设置
                return ps;
            });
        
        // 6. 支付宽表流
        SingleOutputStreamOperator<ProductStats> paymentWideStream = streams
            .get("dwm_payment_wide")
            .map(json -> {
                PaymentWide paymentWide = JSON.parseObject(json, PaymentWide.class);
                ProductStats ps = new ProductStats();
                ps.setSku_id(paymentWide.getSku_id());
                ps.setTs(MyTimeUtil.getTs(paymentWide.getPayment_create_time()));
                ps.getPaidOrderIdSet().add(paymentWide.getOrder_id());
                ps.setPayment_amount(paymentWide.getSplit_total_amount()); // 仍然使用的分摊金额
                
                return ps;
            });
        
        // 7. 评论流
        SingleOutputStreamOperator<ProductStats> commentStream = streams
            .get("dwd_comment_info")
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setTs(MyTimeUtil.getTs(obj.getString("create_time")));
                
                ps.setComment_ct(1L);
                
                if (GmallConstant.APPRAISE_GOOD.equals(obj.getString("appraise"))) {
                    ps.setGood_comment_ct(1L);
                }
                return ps;
            });
        
        // 8. 退款流
        SingleOutputStreamOperator<ProductStats> refundStream = streams
            .get("dwd_order_refund_info")
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
                
                ProductStats ps = new ProductStats();
                ps.setSku_id(obj.getLong("sku_id"));
                ps.setTs(MyTimeUtil.getTs(obj.getString("create_time")));
                
                ps.setRefund_amount(obj.getBigDecimal("refund_amount"));
                ps.getRefundOrderIdSet().add(obj.getLong("order_id"));
                return ps;
            });
        
        return productClickStream.union(
            displayStream,
            orderWideStream,
            favorStream,
            cartStream,
            paymentWideStream,
            refundStream,
            commentStream);
        
    }
}
